<?php
namespace app\admin\controller;

use think\Loader;
use think\Db;
use app\common\tools\jsonRPCClient;

/**
* 用户管理
* @author aierui github  https://github.com/Aierui
* @version 1.0 
*/
class User extends Admin
{


    function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 我的链接
     */
    public function index()
    {
        //获取左区的验证码
        $admin = session('admin')['userinfo'];
        //获取右区的验证码
        $ret = Db::name('user')->where('id',$admin['id'])->find();
        $left = $ret['eth'];
        $flag = 0;
        if($ret['left'])
        {
            $flag = 1;
        }


        $right = $ret['eth'];
        
        $this->assign('left',$left); 
        $this->assign('right',$right);
        $this->assign('flag',$flag);

        return view();
    }

    public function getleft($left)
    {
        
        $user = Db::name('user')->where('eth',$left)->find();
        if($user['left'])
        {
            return $this->getleft($user['left']);
        }else
        {
            return $left;
        }
    }

    public function getethads()
    {
        for ($x=0; $x<=10000; $x++) 
        {
                $client = new jsonRPCClient('http://127.0.0.1:8534', true);

        

                $ret = $client->personal_newAccount("111111");
                
                $data['eth'] = $ret;
                Db::name('eth')->insert($data);
                sleep(2);
        }


    }

    function getBalance($address)
    {
        $method_hash = '0x70a08231';
        $method_param1_hex = str_pad(substr($address, 2), 64, '0', STR_PAD_LEFT);
        $data = $method_hash . $method_param1_hex;
        $params = ['from' => $address, 'to' => self::CONTRACT, 'data' => $data];
        $total_balance = self::eth_call([$params, "latest"]);
        return hexdec($total_balance) / (pow(10, 18));
    }

    function bc_dechex($decimal)
    {
      $result = [];
     
      while ($decimal != 0) {
        $mod = $decimal % 16;
        $decimal = floor($decimal / 16);
        array_push($result, dechex($mod));    
      }
     
      return join(array_reverse($result));
    }


     


    /**
     * 删除
     * @param  string $id 数据ID（主键）
     */
    public function delete($id = 0){
        if(empty($id)){
            return info(lang('Data ID exception'), 0);
        }
        if (intval($id == 1)) {
            return info(lang('Delete without authorization'), 0);
        }
        return Loader::model('User')->deleteById($id);
    }

    /**
     * 修改密码
     */
    public function password(){
        //获取当前登录用户的信息
        $admin = session('admin')['userinfo'];

        //判断当前用户是否登录过期
        if($admin){
            if($this->request->isPost()){

                //接受传输参数
                $data = $this->request->post();

                //支付密码存在则进行下一步
                if($data['pay_password']){
                    

                    //加密支付密码
                    $pay_password = mduser( $data['pay_password'] );
                    $user = Loader::model('User')->getUserById($admin['id'])->toArray();

                    //验证支付密码
                    if($pay_password !== $user['pay_password']){
                        $this->error(info(lang('Pay_password error'),0)['msg']);
                    }

                    //登录密码存在则修改登录密码
                    if(!empty($data['password1']) || !empty($data['password2'])){
                        if($data['password1'] !== $data['password2']){
                            $this->error(info(lang('The two passwords No match'),0)['msg']);
                        }

                        $map['password'] = mduser( $data['password1'] );
                    }
                    //新支付密码存在则修改新支付密码
                    if(!empty($data['pay_password1']) || !empty($data['pay_password2'])){
                        if($data['pay_password1'] !== $data['pay_password2']){
                            $this->error(info(lang('The two paypasswords No match'),0)['msg']);
                        }

                        $map['pay_password'] = mduser( $data['pay_password1'] );
                    }

                    //修改数据
                    $res = Db::name('user')->where('id',$admin['id'])->update($map);
                    if($res){
                        $this->success(info(lang('Edit succeed'),0)['msg']);
                    }else{
                        $this->error(info(lang('Edit failed'),0)['msg']);
                    }

                }else{
                   $this->success(info(lang('Not changed'),0)['msg']); 
                }
                
            }else{

                $this->assign('info',$admin); 
                return $this->fetch();               
            }

        }else{
            $this->error(info(lang('Please login first'),0)['msg']);
        }

        
    }

    /**
     * 二级密码验证
     */
    public function second(){
        
        //获取当前登录用户的信息
        $admin = session('admin')['userinfo'];

        //判断是否为post提交
        if($this->request->isPost()){
            $data = $this->request->param();

            //加密支付密码
            $pay_password = mduser( $data['password'] );

            //验证支付密码
            $user = Loader::model('User')->getUserById($admin['id'])->toArray();
            if($pay_password !== $user['pay_password']){
                $this->error(info(lang('Pay_password error'),0)['msg']);
            }

            session('second','second');

            $url = 'admin'. DS . $data['controller']. DS .$data['action'];

            $this->redirect("$url");
        }

        $this->assign('username',$admin['username']);
        return view();
    }


    /**
     * 修改收款账号
     */
    public function account(){
        
        //获取当前登录用户的信息
        $admin = session('admin')['userinfo'];

        //判断当前用户是否登录过期
        if($admin){

            $controller = request()->controller();
            $action = request()->action();

            // print_r(session('second'));exit;
            //验证支付密码
            if(session('second') !== 'second'){
                $this->redirect('user/second',['controller'=>$controller,'action'=>$action]);
            }


            if($this->request->isPost()){

                //接受传输参数
                $data = $this->request->post();

                if(empty($data['id'])){
                    //新增
                    $res = Db::name('account')->insert($data);
                    if($res){
                    $this->success(info(lang('Add succeed'),0)['msg']);
                }else{
                    $this->error(info(lang('Add failed'),0)['msg']);
                }

                }else{
                    //修改数据
                    $res = Db::name('account')->where('id',$data['id'])->update($data);
                    if($res){
                        $this->success(info(lang('Edit succeed'),0)['msg']);
                    }else{
                        $this->error(info(lang('Edit failed'),0)['msg']);
                    }
                }
                
            }else{
                //获取收款信息
                $account = Db::name('account')->where('uid',$admin['id'])->find();
                $this->assign('admin',$admin); 
                $this->assign('info',$account); 
                return $this->fetch();               
            }

        }else{
            $this->error(info(lang('Please login first'),0)['msg']);
        }

        
    }


    /**
     * 修改资料
     */
    public function details(){

        //获取当前登录用户的信息
        $admin = session('admin')['userinfo'];

        //判断当前用户是否登录过期
        if($admin){

            $controller = request()->controller();
            $action = request()->action();
            //验证支付密码
            if(session('second') !== 'second'){
                $this->redirect('user/second',['controller'=>$controller,'action'=>$action]);
            }

            if($this->request->isPost()){

                //接受传输参数
                $data = $this->request->post();

                //修改数据
                $res = Db::name('user')->where('id',$data['id'])->update($data);
                if($res){
                    $this->success(info(lang('Edit succeed'),0)['msg']);
                }else{
                    $this->error(info(lang('Edit failed'),0)['msg']);
                }

            }else{
                $user = Db::name('user')->where('id',$admin['id'])->find();
                $this->assign('info',$user); 
                return $this->fetch();               
            }

        }else{
            $this->error(info(lang('Please login first'),0)['msg']);
        }

        
    }

    /**
     * 我的红包
     * @return mixed
     */
    public function redbag()
    {
        //获取当前登录用户的信息
        $admin = session('admin')['userinfo'];

        //判断当前用户是否登录过期
        if($admin){

            $controller = request()->controller();
            $action = request()->action();

            if($this->request->isPost()){


            }else{
                //获取收款信息
                $account = Db::name('account')->where('uid',$admin['id'])->find();
                $this->assign('admin',$admin); 
                $this->assign('info',$account); 
                return $this->fetch();               
            }

        }else{
            $this->error(info(lang('Please login first'),0)['msg']);
        }
    }

    /**
     * 点击领取红包
     * @return mixed
     */
    public function getredbag()
    {
        //获取当前登录用户的信息
        $admin = session('admin')['userinfo'];

        $max = Db::name('red_bag')->where('uid',$admin['id'])->max('dt');
        $flag = 0;
        $redbag=null;
        $date = date("Y-m-d");
        if($max)
        {
            $redbag = Db::name('red_bag')->where('uid',$admin['id'])->where('dt',$max)->find();
            
            if($redbag['dt'] == $date)
            {
                $this->error(lang('You have already received the red envelope.'),url('admin/user/redbag'));
            }
        }


        //查询用户信息
        $user = Db::name('user')->where('id',$admin['id'])->find();

        if($user['source'] < 0.0001){
            $this->error(lang('Sorry, your balance is insufficient.'),url('admin/user/redbag'));
        }

        //获取释放利率后的金额
        $release = get_release_rate($user['source']);


        //设置释放记录
        $map = [
            'uid'           => $admin['id'],
            'rate'          => $release['rate'],
            'weighted'      => $release['num'],
            'dt'            => $date
        ];

        // 开启事务
        Db::startTrans();
        try{
            //扣除宝豆增加吉豆录入释放记录
            Db::name('user')->where('id',$admin['id'])->setInc('weighted',$map['weighted']);

            Db::name('user')->where('id',$admin['id'])->setDec('source',$map['weighted']);

            Db::name('red_bag')->insert($map);

            // 更新成功 提交事务
            Db::commit();


        }catch (\Exception $e){
            // 更新失败 回滚事务
            Db::rollback();

            $this->error(lang('Fail to receive'),url('admin/user/redbag'));
        }

        $w = Db::name('red_bag')->where('dt',$date)->sum('weighted');
        $this->assign('weighted',$map['weighted']);
        $this->assign('w',$w);
        return $this->fetch();
    }




    public function getredbaglist()
    {
        if(!request()->isAjax()) {
            $this->error(lang('Request type error'), 4001);
        }
        $request = request()->param();
        unset($request['/admin/user/getredbaglist']);
        
        $admin = session('admin')['userinfo'];
        $info = Db::name('user')->where('id',$admin['id'])->find();

        $request = $this->fmtRequest($request);
        $data = Db::name('red_bag')->order('id desc')->where('uid',$admin['id'])->where( $request['map'] )->select();

        
        //$data = $this->_fmtData( $data );
        //$data = $this->fmtBuylistData( $data );

        //$data['total'] = 100;
        return $data;
        
    }

    protected function fmtRequest( $request = [] )
    {
        if( empty($request) ) {
            return $request;
        }
        $offset = 0;
        if (isset($request['offset']) && is_numeric($request['offset']) ) {
            $offset = $request['offset'];
            unset($request['offset']);
        }
        $limit = 5;
        if (isset($request['limit']) && is_numeric($request['limit']) ) {
            $limit = $request['limit'];
            unset($request['limit']);
        }
        $ret = [
            'offset'=>$offset,
            'limit'=>$limit,
            'map'=>$request
        ];
        return $ret;
    }


    
   
}